<template>
  <CustomNav title="个人中心"></CustomNav>
  <view class="container">
    <view class="content">
      <view class="row avatar-wrapper">
        <button open-type="chooseAvatar" @chooseavatar="handleUploadAvatar">
          <view class="left"> 头像 </view>
          <view class="right">
            <u--image
              :lazy-load="true"
              shape="circle"
              :showLoading="true"
              :src="avatarUrl"
              width="50px"
              height="50px"
            >
              <template v-slot:loading>
                <u-loading-icon color="#ccc"></u-loading-icon>
              </template>
              <template #error>
                <view style="font-size: 24rpx">加载失败</view>
              </template>
            </u--image>
            <i class="iconfont icon-arrow-right"></i>
          </view>
        </button>
      </view>
      <view class="row" @click="jumpPage('/pagesC/modifyNickname/index')">
        <view class="left"> 姓名 </view>

        <!--  -->
        <view class="right nickName">
          <view class="text">
            <view class="text_">
              <view>{{ username }}</view>
              <i class="iconfont icon-arrow-right"></i>
            </view>
          </view>
        </view>
      </view>
      <view class="row" @click="handleUpdateGender">
        <view class="left"> 性别 </view>
        <view class="right">
          <view class="text">{{ formatGender(gender) }}</view>
          <i class="iconfont icon-arrow-right"></i>
        </view>
      </view>
      <view class="row">
        <view class="left"> 学号</view>
        <view class="right">
          <view class="text">{{ studentNumber || "#undefined" }}</view>
          <!-- <i class="iconfont icon-arrow-right"></i> -->
        </view>
      </view>
      <view class="row" @click="handleShowPassword(password)">
        <view class="left">后台管理系统密码</view>
        <view class="right">
          <!-- <view class="text">{{ password }}</view> -->
          <i class="iconfont icon-arrow-right"></i>
        </view>
      </view>

      <view
        class="row"
        @click="jumpPage('/pagesC/personalizedSignature/index')"
        v-if="homeStore.checkShowV"
      >
        <view class="left"> 个性签名 </view>
        <view class="right sign">
          <view class="text">
            <view class="text_">
              <view>{{ signature }}</view>
              <i class="iconfont icon-arrow-right"></i>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="content logOut" @click="logOut"> 退出登录 </view>
  </view>

  <view class="alert">温馨提示：每月只有三次修改机会</view>
  <!-- <u-modal
    :show="showModal"
    :title="modalTitle"
    :content="modalContent"
  ></u-modal> -->

  <van-dialog id="van-dialog" />
</template>

<script setup>
import CustomNav from "@/components/CustomNav";
import { getItem, clearAll, updateItem } from "../../utils/localStorage";
import { Alert, jumpPage, unAlert, formatGender } from "../../utils/tool";
import { logoutApi } from "@/api/user";
import env from "@/utils/env";
import { getToken } from "../../utils/auth";
import { updateUserData } from "@/api/user";
import useHomeStore from "@/store/modules/home";

const homeStore = useHomeStore();

// 头像
const avatarUrl = ref("");
// 姓名
const username = ref("");
// 性别
const gender = ref(0);
// 学号
const studentNumber = ref("");
// 学号
const password = ref("");
// 个性签名
const signature = ref("");

onShow(() => {
  // 头像
  avatarUrl.value = getItem("userInfo").headPath;
  // 姓名
  username.value = getItem("userInfo").username;
  // 性别
  gender.value = getItem("userInfo").gender;
  // 学号
  studentNumber.value = getItem("userInfo").number;
  // 后台管理系统密码
  // password.value = getItem("userInfo").password;
  // sxpi@后四位
  password.value = `sxpi@${String(getItem("userInfo").phone).substring(11, 7)}`;

  // 个性签名
  signature.value = getItem("userInfo").description ?? "此人很懒~";
});

// 更换头像
const handleUploadAvatar = (e) => {
  console.log("e：", e);
  const url = e.detail.avatarUrl;
  uni.uploadFile({
    url: `${env.baseUrl}/studio/user/updateHead/${getItem("userInfo").id}`,
    fileType: "image",
    filePath: String(url),
    name: "file",
    header: {
      Authorization: getToken(), //携带token
    },
    formData: {
      id: getItem("userInfo").id,
    },
    success(res) {
      let res2 = JSON.parse(res.data);

      console.log("success：", res2.code);

      if (res2.code == 200) {
        console.log("更换成功");
        unAlert();
        Alert("更换成功", "success");
        avatarUrl.value = url;

        const successUrl = `${env.baseUrl}/studio/img/head/${res2.data.headPath}`;
        updateItem("userInfo", "headPath", successUrl);
      }
    },
    complete(res) {
      let res2 = JSON.parse(res.data);

      Alert("更换中...", "loading", 0, true);

      if (res2.code == 200) {
        Alert("更换成功", "success", 500);
      }
    },
  });
};

// 修改性别
const handleUpdateGender = () => {
  uni.showModal({
    title: "提示",
    content: "确认修改性别吗",
    success: function (res) {
      if (res.confirm) {
        console.log("用户点击确定");

        uni.showActionSheet({
          itemList: ["男", "女"],
          success: async (res) => {
            console.log("选中了第" + (res.tapIndex + 1) + "个按钮");
            console.log("index：", res);
            console.log("gender.value:", gender.value);

            // 选择的与之前一致不可发请求，进行拦截
            if (!gender.value == res.tapIndex) {
              Alert("不可选择同一个");
              return;
            } else {
              Alert("准备发送请求！！！");
            }

            // if (gender.value == 1) {
            //   // 女
            //   if (res.tapIndex == 0) {
            //     // 选的是女
            //     Alert("不可选择同一个");
            //     return;
            //   }
            // }

            const selectResult = res.tapIndex ? 0 : 1;
            console.log("selectResult:", selectResult);

            Alert("加载中", "loading", 0, true);

            const result = await updateUserData({
              id: getItem("userInfo").id,
              gender: selectResult,
            });

            if (result.data.code == 200) {
              Alert("修改成功", "success");
              updateItem("userInfo", "gender", selectResult);
              gender.value = selectResult;
            }

            console.log("修改结果:", result);
          },
          fail: function (res) {
            console.log(res.errMsg);
          },
        });
      } else if (res.cancel) {
        console.log("用户点击取消");
        Alert("已取消");
      }
    },
  });
};

// 查看后台管理系统密码
const handleShowPassword = (pw) => {
  uni.setClipboardData({
    data: pw,
    showToast: false,
    success: () => {
      unAlert();
      uni.showModal({
        showCancel: false,
        title: "密码请勿泄露",
        content: pw,
        confirmText: "复制",
        success() {
          Alert("复制成功", "success");
        },
      });
    },
    fail: () => {
      uni.showToast({
        title: "复制失败！",
      });
    },
  });
};

// 退出登录
const logOut = () => {
  // 先发起振动提醒用户
  uni.vibrateLong({
    success: function () {
      uni.showModal({
        title: "提示",
        content: "确认退出登录吗？",
        success: async function (res) {
          Alert("退出登录中", "loading", 0, true);

          if (res.confirm) {
            // 发请求
            const result = await logoutApi();

            console.log("result：", result);

            if (result.data.code == 200) {
              // console.log('退出登录成功');
              Alert("退出登录成功", "success");

              // 清理本地所有用户相关的缓存
              clearAll();

              setTimeout(() => {
                // 跳转到首页（逻辑在updateUserInfo里）
                // 返回到首页
                uni.reLaunch({
                  url: "/pages/index/index",
                });
              }, 1000);
            } else {
              Alert("退出登录失败，请稍后重试！");
            }
          } else if (res.cancel) {
            // console.log('退出登录失败');
            Alert("已取消");
          }
        },
      });
    },
  });
};
</script>

<style lang="scss">
.container {
  width: 750rpx;
  // min-height: 100vh;
  background-color: #f5f5f5;
  padding: 25rpx 20rpx;
  min-height: 88vh;

  .content {
    background-color: #fff;
    box-shadow: 0 0 10px $shadow;
    padding: 0 40rpx;
    border-radius: 15rpx;

    .row {
      width: 100%;
      /* height: 150rpx; */
      /* border:1px solid red; */
      border-bottom: 1px solid #dcdcdc;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 35rpx 0;
      font-size: 30rpx;
      /* font-weight: 700; */

      &:last-child {
        border: none;
      }

      .left {
        /* width: 420rpx; */
      }

      .right {
        /* width: 460rpx; */
        display: flex;
        align-items: center;
        color: #b5b5b5;

        .text {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;

          .text_ {
            display: flex;
            align-items: center;
          }
        }

        .iconfont {
          margin-left: 20rpx;
        }

        input {
          width: 460rpx;
        }
      }

      /* 个性签名 */
      .sign {
        /* width: 460rpx; */
      }
    }

    /* 头像 */
    .avatar-wrapper {
      button {
        width: 100%;
        height: 100%;
        padding: 0;
        background: transparent;
        /*设置背景颜色一致*/
        border-color: transparent;
        /*设置边框颜色一致*/
        display: flex;
        align-items: center;
        justify-content: space-between;

        &::after {
          border: none;
          /*设置边框取消*/
        }
      }
    }
  }

  .logOut {
    padding: 25rpx 40rpx;
    text-align: center;
    margin-top: 20rpx;
    transition: all 0.2s;

    &:active {
      background-color: rgba(0, 0, 0, 0.1);
      /* border:1px solid #fff; */
    }
  }
}

.alert {
  width: 750rpx;
  text-align: center;
  position: fixed;
  bottom: 18rpx;
  font-size: 28rpx;
  /* background-color: $white; */
  color: #807d7d;

  text-shadow: 2px 3px 1px #bdbbbb;
}
</style>
